package org.club.Service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.club.Service.ActivityService;
import org.club.Service.FileOssService;
import org.club.common.model.dto.*;
import org.club.common.model.entity.AnnouncementReadCountResult;
import org.club.common.model.vo.*;
import org.club.common.util.EmailUtils;
import org.club.mapper.ActivityMapper;
import org.club.common.model.entity.Activity;
import org.club.common.model.entity.BusinessException;
import org.club.common.model.entity.ClubMemberInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.*;

@Service
@Slf4j
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private FileOssService fileOssService;//文件上传
    @Autowired
    private EmailUtils emailUtils;


    //查询该用户管理社团的信息
    @Override
    public CommunityDetailsVo selectClubsTest(Long userId) {
        if (userId == null || userId == 0) {
            throw new BusinessException(400, "参数为空");
        }
        try {
            CommunityDetailsVo clubInfoVO = activityMapper.selectclubsTest(userId);
            if (clubInfoVO == null) {
                throw new BusinessException(400, "该用户暂无社团信息");
            }
            return clubInfoVO;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(400, "查询失败,请确认该用户是否为社团管理员");
        }
    }


    /**
     * 创建活动
     *
     * @param request
     * @param file
     */
    @Override
    @Transactional
    public void createActivity(ActivityRequest request, MultipartFile file) {
        // 打印请求信息
        log.info("创建活动请求参数: {}", request);
        if (request.getTitle() == null || request.getTitle().isEmpty()) {
            throw new BusinessException(400, "活动标题不能为空");
        }
        //活动时间不能为空
        if (request.getStartTime() == null || request.getEndTime() == null) {
            throw new BusinessException(400, "活动时间不能为空");
        }
        if (request.getStartTime().isBefore(LocalDateTime.now())) {
            throw new BusinessException(400, "活动开始时间不能早于当前时间");
        }
        if (request.getEndTime().isBefore(request.getStartTime())) {
            throw new BusinessException(400, "活动结束时间不能早于开始时间");
        }
        if (request.getClubId() == null || request.getClubId() <= 0) {
            log.info("社团ID为空{}", request.getClubId());
            throw new BusinessException(400, "社团ID不能为空");
        }
        //验证该社团是否存在于clubs表里面
        Integer s = activityMapper.selectClubs(request.getClubId());
        String FileUrl = null;
        if (s == 1) {
            try {
                FileUrl = fileOssService.uploadToOss(file);
                request.setCoverUrl(FileUrl);
                Integer i = activityMapper.createActivity(request);
                if (i != 1) {
                    throw new BusinessException(400, "创建活动失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                fileOssService.deleteFileFromOss(FileUrl);
                throw new BusinessException(400, "创建活动失败");
            }
        } else {
            throw new BusinessException(400, "该社团不存在");
        }
    }

    //查询社团发布的活动
    @Override
    public List<ActivitiesVO> searchActivities(ActivityQueryDTO activityQueryDTO) {
        if (activityQueryDTO.getClubId() == null) {
            throw new BusinessException(400, "信息缺失");
        }
        //验证时间
        Boolean isValid = false;
        if (activityQueryDTO.getStartTime() != null && activityQueryDTO.getEndTime() != null) {
            isValid = true;
        }
        if (isValid && activityQueryDTO.getStartTime().isAfter(activityQueryDTO.getEndTime())) {
            throw new BusinessException(400, "开始时间不能晚于结束时间");
        }
        List<Activity> activities = activityMapper.searchActivities(activityQueryDTO);

        List<ActivitiesVO> activitiesVO = activities.stream().map(activity -> new ActivitiesVO(activity.getId(), activity.getTitle(), activity.getDescription(), activity.getCoverUrl(), activity.getStartTime().toString(), activity.getEndTime().toString(), activity.getStatus().toString(), activity.getMaxParticipants(), activity.getCreatedAt())).toList();
        return activitiesVO;
    }

    @Override
    @Transactional
    public void updateActivity(ActivityRequest request, MultipartFile file) {
        Boolean isValid = false;
        if (request.getStartTime() != null && request.getEndTime() != null) {
            isValid = true;
        }
        if (isValid && request.getStartTime().isAfter(request.getEndTime())) {
            throw new BusinessException(400, "开始时间不能晚于结束时间");
        }
        String FileUrl = null;
        try {
            if (!(file.isEmpty() && file.getSize() == 0)) {
                //查询该活动的图片地址
                String oldFileUrl = activityMapper.selectActivityCoverUrl(request.getId());
                fileOssService.deleteFileFromOss(oldFileUrl);
                FileUrl = fileOssService.uploadToOss(file);
            }
            if (isValid) {
                request.setStatus("3");
            }
            request.setCoverUrl(FileUrl);
            log.info("更新后的图片地址{}", request.getCoverUrl());
            Integer i = activityMapper.updateActivity(request);
            if (i != 1) {
                throw new BusinessException(400, "修改活动失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("将要删除的图片地址{}", request.getCoverUrl());
            fileOssService.deleteFileFromOss(request.getCoverUrl());
            throw new BusinessException(400, "修改活动失败");
        }

    }

    @Override
    @Transactional
    public void deleteActivities(Long ids) {
        if (ids == null) {
            throw new BusinessException(400, "信息缺失");
        }
        //查询活动图片地址
        String coverUrls = activityMapper.selectActivityCoverUrls(ids);
        log.info("查询到的图片地址{}", coverUrls);
        try {
            //删除图片
            fileOssService.deleteFileFromOss(coverUrls);
            //删除活动
            Integer i = activityMapper.deleteActivity(ids);
            if (i != 1) {
                throw new BusinessException(400, "删除活动失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(400, "删除活动失败");
        }
    }

    @Override
    public List<ApplicantsVO> getRegistration(Long activityId) {
        if (activityId == null) {
            throw new BusinessException(400, "信息缺失");
        }
        List<ApplicantsVO> activities = activityMapper.getRegistration(activityId);
        log.info("查询报名信息：{}", activities);

        return activities;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reviewRegistrations(List<Long> userIds, Integer status, Long activityId) {
        if (userIds == null || status == null) {
            throw new BusinessException(400, "信息缺失");
        }
        if (!status.equals(2) && !status.equals(1)) {
            throw new BusinessException(400, "状态值错误");
        }
        if (activityId == null) {
            throw new BusinessException(400, "信息缺失");
        }
        //验证该活动人数是否超过最大人数
        Integer o = activityMapper.selectRemainingSpots(activityId);
        if (o <= 0) {
            //修改活动状态
            activityMapper.updateActivityStatus(activityId, 5);
            throw new BusinessException(400, "报名人数已满");
        }
        try {
            //将剩余报名人数和当前提交的审核人数进行比较，比如：当前提交了9个报名，剩余报名人数为5，则取前5人进行审核
            if (userIds.size() > o) {
                userIds = userIds.subList(0, o);
            }
            Integer i = activityMapper.reviewRegistrations(userIds, status, activityId);
            //更新活动表里面的报名人数字段数据
            activityMapper.updateActivityNumber_applicants(activityId, i);
            log.info("审核返回值{}", i);
            if (i == 0) {
                throw new BusinessException(400, "审核失败,请重试");
            }
            //查询出社团成员信息（邮箱、姓名）
            List<Map<String, String>> userInfos = activityMapper.getEmailAndName(userIds);
            //查询该成员报名的活动名称
            String activityName = activityMapper.getActivityName(activityId);
            //发送邮件
            for (Map<String, String> userInfo : userInfos) {
                String name = userInfo.get("real_name");
                String email = userInfo.get("email");
                emailUtils.sendSimpleMail(email, "社团活动报名审核结果", name + "同学 您好，您的社团活动报名审核结果为:已通过，活动名称为：" + activityName + "，请登录社团平台查看详情。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(400, "审核失败,请重试");
        }

    }
    //查询该活动的报名信息
    @Override
    public ActivityRegistrationReviewVO getApplicants(Long activityId) {
        Map<String, Object> result = activityMapper.selectActivityNumber_applicants(activityId);
        if(result==null){
            throw new BusinessException(400, "该活动无报名信息");
        }
        Number maxParticipantsNum = (Number) result.get("max_participants");
        Number currentApplicantsNum = (Number) result.get("current_applicants");
        Number remainingSpotsNum = (Number) result.get("remaining_spots");
        Number approvedApplicantsNum = (Number) result.get("approved_applicants");
        Long maxParticipants = maxParticipantsNum != null ? maxParticipantsNum.longValue() : 0L;
        Long currentApplicants = currentApplicantsNum != null ? currentApplicantsNum.longValue() : 0L;
        Long remainingSpots = remainingSpotsNum != null ? remainingSpotsNum.longValue() : 0L;
        Long approvedApplicants = approvedApplicantsNum != null ? approvedApplicantsNum.longValue() : 0L;
        log.info("活动报名审核结果：最大报名人数为：{},当前报名人数为：{},剩余报名人数为：{},已通过报名人数为：{}", maxParticipants, currentApplicants, remainingSpots, approvedApplicants);
        return new ActivityRegistrationReviewVO(maxParticipants, currentApplicants, remainingSpots, approvedApplicants);
    }

    //查询社团成员
    @Override
    public List<ClubMemberInfo> getClubsUser(ClubMemberInfoDto clubMemberInfoDto) {
        if (clubMemberInfoDto.getClubId() == null) {
            throw new BusinessException(400, "信息缺失");
        }
        Boolean isVa = false;
        if (clubMemberInfoDto.getEndTime() != null && clubMemberInfoDto.getStartTime() != null) {
            isVa = true;
        }
        if (isVa && clubMemberInfoDto.getEndTime().isBefore(clubMemberInfoDto.getStartTime())) {
            throw new BusinessException(400, "结束时间早于开始时间");
        }
        List<ClubMemberInfo> applicants = activityMapper.getClubsUser(clubMemberInfoDto);
        log.info("applicants:{}", applicants);
        return applicants;
    }

    @Override
    public byte[] exportMembers(ClubMemberInfoDto clubMemberInfoDto) {
        if (clubMemberInfoDto.getClubId() == null) {
            throw new BusinessException(400, "社团ID不能为空");
        }
        if (clubMemberInfoDto.getFormat() == null) {
            throw new BusinessException(400, "导出格式不能为空");
        }

        // 获取成员数据
        List<ClubMemberInfo> members = getClubsUser(clubMemberInfoDto);
        if (members.isEmpty()) {
            throw new BusinessException(400, "没有可导出的数据");
        }

        try {
            String format = clubMemberInfoDto.getFormat().toLowerCase();
            if (format.equals("xlsx")) {
                return exportToExcel(members);
            } else if (format.equals("csv")) {
                return exportToCsv(members);
            } else if (format.equals("txt")) {
                return exportToTxt(members);
            } else {
                throw new BusinessException(400, "不支持的导出格式，支持的格式有：xlsx、csv、txt");
            }
        } catch (Exception e) {
            log.error("导出失败", e);
            throw new BusinessException(500, "导出失败：" + e.getMessage());
        }
    }

    private byte[] exportToExcel(List<ClubMemberInfo> members) throws Exception {
        try (XSSFWorkbook workbook = new XSSFWorkbook()) {
            XSSFSheet sheet = workbook.createSheet("社团成员");

            // 创建表头
            Row headerRow = sheet.createRow(0);
            String[] headers = {"用户名", "真实姓名", "手机号", "邮箱", "加入时间", "状态"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 填充数据
            int rowNum = 1;
            for (ClubMemberInfo member : members) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(member.getUsername());
                row.createCell(1).setCellValue(member.getRealName());
                row.createCell(2).setCellValue(member.getPhone());
                row.createCell(3).setCellValue(member.getEmail());
                row.createCell(4).setCellValue(member.getJoinTime().toString());
                row.createCell(5).setCellValue(member.getStatus() == 0 ? "正常" : "已退出");
            }

            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }

            // 写入字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            return outputStream.toByteArray();
        }
    }

    private byte[] exportToCsv(List<ClubMemberInfo> members) {
        StringBuilder csv = new StringBuilder();
        // 添加表头
        csv.append("用户名,真实姓名,手机号,邮箱,加入时间,状态\n");

        // 添加数据行
        for (ClubMemberInfo member : members) {
            csv.append(String.format("%s,%s,%s,%s,%s,%s\n",
                    member.getUsername(),
                    member.getRealName(),
                    member.getPhone(),
                    member.getEmail(),
                    member.getJoinTime(),
                    member.getStatus() == 0 ? "正常" : "已退出"
            ));
        }

        return csv.toString().getBytes(StandardCharsets.UTF_8);
    }

    private byte[] exportToTxt(List<ClubMemberInfo> members) {
        StringBuilder txt = new StringBuilder();
        // 添加表头
        txt.append("用户名\t真实姓名\t手机号\t邮箱\t加入时间\t状态\n");

        // 添加数据行
        for (ClubMemberInfo member : members) {
            txt.append(String.format("%s\t%s\t%s\t%s\t%s\t%s\n",
                    member.getUsername(),
                    member.getRealName(),
                    member.getPhone(),
                    member.getEmail(),
                    member.getJoinTime(),
                    member.getStatus() == 0 ? "正常" : "已退出"
            ));
        }

        return txt.toString().getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public byte[] exportRegistrations(RegistrationExportRequest request) {
        if (request.getActivityId() == null) {
            throw new BusinessException(400, "活动ID不能为空");
        }
        if (request.getUserIds() == null || request.getUserIds().isEmpty()) {
            throw new BusinessException(400, "请选择要导出的报名记录");
        }
        if (request.getFormat() == null) {
            throw new BusinessException(400, "导出格式不能为空");
        }

        // 获取报名数据
        List<ApplicantsVO> registrations = activityMapper.getRegistrationByIds(request.getActivityId(), request.getUserIds());
        if (registrations.isEmpty()) {
            throw new BusinessException(400, "没有可导出的数据");
        }

        try {
            String format = request.getFormat().toLowerCase();
            if (format.equals("xlsx")) {
                return exportRegistrationsToExcel(registrations);
            } else if (format.equals("csv")) {
                return exportRegistrationsToCsv(registrations);
            } else if (format.equals("txt")) {
                return exportRegistrationsToTxt(registrations);
            } else {
                throw new BusinessException(400, "不支持的导出格式，支持的格式有：xlsx、csv、txt");
            }
        } catch (Exception e) {
            log.error("导出失败", e);
            throw new BusinessException(500, "导出失败：" + e.getMessage());
        }
    }

    //移除成员（软删除）
    @Override
    @Transactional
    public void removeMember(RemoveMemberDto removeMemberDto) {
        if (removeMemberDto.getAdminID() == null || removeMemberDto.getClubID() == null || removeMemberDto.getDeleUserID() == null || removeMemberDto.getStatus() == null) {
            throw new BusinessException(400, "参数不能为空");
        }
        //验证adminID是否为clubID的管理员
        if (activityMapper.selectAdmin(removeMemberDto.getAdminID(), removeMemberDto.getClubID()) != 1) {
            throw new BusinessException(400, "您不是该社团的管理员,无权删除");
        }
        //验证deleUserID是否为clubID的成员
        if (activityMapper.selectClubsUser(removeMemberDto.getClubID(), removeMemberDto.getDeleUserID()) != 1) {
            throw new BusinessException(400, "该用户不是社团成员,无法删除");
        }
        try {
            Integer i = activityMapper.removeMember(removeMemberDto);
            if (i == 0) {
                throw new BusinessException(400, "删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(400, "删除失败" + e.getMessage());
        }
    }

    //社团公告
    @Override
    public List<AnnouncementVO> getCommunityAnnouncements(ClubsAnnouncementDto clubsAnnouncenmentdto) {
        // 设置分页参数
        PageHelper.startPage(clubsAnnouncenmentdto.getPageNum(), clubsAnnouncenmentdto.getPageSize());
        List<AnnouncementVO> announcements = activityMapper.getCommunityAnnouncements(clubsAnnouncenmentdto);
        // 获取分页信息
        PageInfo<AnnouncementVO> pageInfo = new PageInfo<>(announcements);
        if (announcements.isEmpty()) {
            throw new BusinessException(400, "社团公告为空");
        }
        return announcements;
    }

    //获取社团所有的成员id
    @Override
    public List<Long> getClubsUserId(Long clubId) {
        if (clubId == null) {
            throw new BusinessException(400, "社团ID不能为空");
        }
        List<Long> userIds = activityMapper.getClubsUserId(clubId);
        if (userIds.isEmpty()) {
            throw new BusinessException(400, "社团成员为空");
        }
        return userIds;
    }


    private byte[] exportRegistrationsToExcel(List<ApplicantsVO> registrations) throws Exception {
        try (XSSFWorkbook workbook = new XSSFWorkbook()) {
            XSSFSheet sheet = workbook.createSheet("报名列表");

            // 创建表头
            Row headerRow = sheet.createRow(0);
            String[] headers = {"用户名", "真实姓名", "手机号", "邮箱", "报名时间", "审核状态"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 填充数据
            int rowNum = 1;
            for (ApplicantsVO registration : registrations) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(registration.getUsername());
                row.createCell(1).setCellValue(registration.getRealName());
                row.createCell(2).setCellValue(registration.getPhone());
                row.createCell(3).setCellValue(registration.getEmail());
                row.createCell(4).setCellValue(registration.getRegistrationTime().toString());
                row.createCell(5).setCellValue(getRegistrationStatusText(registration.getRegistrationStatus()));
            }

            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }

            // 写入字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            return outputStream.toByteArray();
        }
    }

    private byte[] exportRegistrationsToCsv(List<ApplicantsVO> registrations) {
        StringBuilder csv = new StringBuilder();
        // 添加表头
        csv.append("用户名,真实姓名,手机号,邮箱,报名时间,审核状态\n");

        // 添加数据行
        for (ApplicantsVO registration : registrations) {
            csv.append(String.format("%s,%s,%s,%s,%s,%s\n",
                    registration.getUsername(),
                    registration.getRealName(),
                    registration.getPhone(),
                    registration.getEmail(),
                    registration.getRegistrationTime(),
                    getRegistrationStatusText(registration.getRegistrationStatus())
            ));
        }

        return csv.toString().getBytes(StandardCharsets.UTF_8);
    }

    private byte[] exportRegistrationsToTxt(List<ApplicantsVO> registrations) {
        StringBuilder txt = new StringBuilder();
        // 添加表头
        txt.append("用户名\t真实姓名\t手机号\t邮箱\t报名时间\t审核状态\n");

        // 添加数据行
        for (ApplicantsVO registration : registrations) {
            txt.append(String.format("%s\t%s\t%s\t%s\t%s\t%s\n",
                    registration.getUsername(),
                    registration.getRealName(),
                    registration.getPhone(),
                    registration.getEmail(),
                    registration.getRegistrationTime(),
                    getRegistrationStatusText(registration.getRegistrationStatus())
            ));
        }

        return txt.toString().getBytes(StandardCharsets.UTF_8);
    }


    //    定时任务
    @Override
    public boolean updateActivityStatus(Long activityId, Integer status) {
        return activityMapper.updateActivityStatus(activityId, status) > 0;
    }

    @Override
    public List<Activity> getAllPublishedActivities() {
        return activityMapper.findPublishedActivities();
    }

    @Override
    public void checkAndUpdateEndedActivities() {
        // 获取当前时间
        Date now = new Date();

        // 查找所有已经结束的活动
        List<Activity> endedActivities = activityMapper.findActivitiesEndedBefore(now);

        // 更新活动状态为已结束(4)
        for (Activity activity : endedActivities) {
            activityMapper.updateActivityStatus(activity.getId(), 4);
        }
    }

    @Override
    public List<Activity> getAllUnpublishedActivities() {
        return activityMapper.findUnpublishedActivities();
    }

    @Override
    public void checkAndUpdateStartingActivities() {
        // 获取当前时间
        Date now = new Date();
        // 查找所有应该开始的活动（未发布但开始时间已到）
        List<Activity> startingActivities = activityMapper.findActivitiesToStartBefore(now);
        // 更新活动状态为已发布(1)
        for (Activity activity : startingActivities) {
            activityMapper.updateActivityStatus(activity.getId(), 1);
        }
    }

    //更新社团信息
    @Override
    @Transactional
    public void updateClubInfo(LiteratureClubDto literatureClub, MultipartFile file) {
        log.info("需要更新的信息{}", literatureClub);
        // 参数校验
        if (literatureClub == null) {
            throw new BusinessException(400, "社团信息不能为空");
        }
        if (literatureClub.getClubId() == null) {
            throw new BusinessException(400, "社团ID不能为空");
        }
        // 验证社团是否存在
        Integer count = activityMapper.selectClubs(literatureClub.getClubId());
        if (count == null || count == 0) {
            throw new BusinessException(404, "社团不存在");
        }

        String clubLogoUrl = null;
        String originalClubLogoUrl = null;

        try {
            // 获取原始的图片路径
            originalClubLogoUrl = activityMapper.selectClubCoverUrl(literatureClub.getClubId());

            // 检查是否上传了新图片
            boolean hasNewImage = file != null && !file.isEmpty() && file.getSize() > 0 &&
                    !"application/octet-stream".equals(file.getContentType());

            if (hasNewImage) {
                // 上传新图片
                clubLogoUrl = fileOssService.uploadToOss(file);
                literatureClub.setClubLogoUrl(clubLogoUrl);

                // 删除原始图片
                if (originalClubLogoUrl != null && !originalClubLogoUrl.isEmpty()) {
                    fileOssService.deleteFileFromOss(originalClubLogoUrl);
                }
            }
            // 更新社团信息
            int result = activityMapper.updateClubInfo(literatureClub);
            if (result <= 0) {
                throw new BusinessException(500, "更新社团信息失败");
            }
            log.info("社团信息更新成功，社团ID: {}", literatureClub.getClubId());
        } catch (Exception e) {
            log.error("更新社团信息出错: {}", e.getMessage(), e);
            // 如果上传了新图片但更新失败，则删除新上传的图片
            if (clubLogoUrl != null && !clubLogoUrl.isEmpty()) {
                fileOssService.deleteFileFromOss(clubLogoUrl);
            }
            throw new BusinessException(500, "更新社团信息失败: " + e.getMessage());
        }
    }

    @Override
    public void createComment(ActivityCommentDTO commentDTO) {
        if (commentDTO == null) {
            throw new BusinessException(400, "评论信息不能为空");
        }
        if (commentDTO.getReplierId() == null) {
            throw new BusinessException(400, "评论者ID不能为空");
        }
        Integer i = activityMapper.createComment(commentDTO);
        log.info("创建评论成功，活动ID: {}, 用户ID: {}, 内容: {}", commentDTO.getActivityId(),
                commentDTO.getReplierId(), commentDTO.getContent());
        if (i <= 0) {
            throw new BusinessException(500, "创建评论失败");
        }
    }

    //获取评论
    @Override
    public List<ActivityCommentVO> getComments(Long activityId) {
        // 1. 查询所有评论
        List<ActivityCommentVO> allComments = activityMapper.getComments(activityId);

        // 2. 构建id->评论的Map
        Map<Integer, ActivityCommentVO> idMap = new HashMap<>();
        for (ActivityCommentVO comment : allComments) {
            comment.setReplies(new ArrayList<>());
            idMap.put(comment.getId(), comment);
        }

        // 3. 组装树结构
        List<ActivityCommentVO> rootComments = new ArrayList<>();
        for (ActivityCommentVO comment : allComments) {
            if (comment.getParentId() == null) {
                rootComments.add(comment);
            } else {
                ActivityCommentVO parent = idMap.get(comment.getParentId());
                if (parent != null) {
                    parent.getReplies().add(comment);
                }
            }
        }
        return rootComments;
    }

    //  获取有关社团的消息
    @Override
    public List<MessageVO> getMessages(Long adminId, Integer readStatus) {
        if (adminId == null) {
            throw new BusinessException(400, "管理员ID不能为空");
        }
        log.info("获取有关社团的消息，管理员ID: {}, 读取状态: {}", adminId, readStatus);
        List<MessageVO> messages = activityMapper.getMessages(adminId, readStatus);
        return messages;
    }

    //  更新消息的读取状态
    @Override
    public void updateMessageReadStatus(UpdateMessageReadStatusDto updateMessageReadStatusDto) {
        if (updateMessageReadStatusDto.getMessageIds() == null || updateMessageReadStatusDto.getMessageIds().isEmpty()) {
            throw new BusinessException(400, "消息ID不能为空");
        }
        if (updateMessageReadStatusDto.getAdminId() == null) {
            throw new BusinessException(400, "管理员ID不能为空");
        }
        Integer i = activityMapper.updateMessageReadStatus(updateMessageReadStatusDto.getMessageIds(), updateMessageReadStatusDto.getAdminId());
        log.info("更新消息的读取状态，消息ID: {}, 管理员ID: {}", updateMessageReadStatusDto.getMessageIds(), updateMessageReadStatusDto.getAdminId());
        if (i <= 0) {
            throw new BusinessException(500, "更新消息的读取状态失败");
        }
    }

    //  获取公告的已读数和未读数
    @Override
    public MessageSummaryVO getAnnouncementReadCounts(AnnouncementReadCountsDto announcementReadCountsDto) {
        if (announcementReadCountsDto.getAnnouncementIds() == null || announcementReadCountsDto.getAnnouncementIds().isEmpty()) {
            throw new BusinessException(400, "公告ID不能为空");
        }

        // 1. 调用Mapper获取公告阅读统计列表
        List<AnnouncementReadCountResult> resultList = activityMapper.getAnnouncementReadCountList(announcementReadCountsDto.getAnnouncementIds());

        // 2. 构建 MessageSummaryVO 和其内部的 Map
        MessageSummaryVO messageSummaryVO = new MessageSummaryVO();
        Map<String, MessageCountVO> messageCountsMap = new HashMap<>();

        // 3. 遍历结果列表，填充 Map
        if (resultList != null) {
            for (AnnouncementReadCountResult result : resultList) {
                MessageCountVO messageCountVO = new MessageCountVO();
                messageCountVO.setReadCount(result.getReadCount());
                messageCountVO.setUnreadCount(result.getUnreadCount());

                // 使用公告ID的字符串形式作为Map的键
                messageCountsMap.put(result.getAnnouncementId().toString(), messageCountVO);
            }
        }

        // 4. 将构建好的 Map 设置到 MessageSummaryVO 中
        messageSummaryVO.setMessageCounts(messageCountsMap);

        // 5. 返回 MessageSummaryVO
        return messageSummaryVO;
    }

    //更新个人信息
    @Override
    @Transactional
    public UserVo updatePersonalInfo(UpdatePersonalInfoRequestDto updatePersonalInfoRequestDto, MultipartFile file) {
        if (updatePersonalInfoRequestDto.getUserId() == null) {
            throw new BusinessException(400, "用户ID不能为空");
        }
        //检查该用户是否存在
        Integer i = activityMapper.selectUser(updatePersonalInfoRequestDto.getUserId());
        if (i == 0) {
            throw new BusinessException(400, "用户不存在");
        }
        try {
            if (file != null) {
                //上传图片到OSS
                String s = fileOssService.uploadToOss(file);
                if (s != null) {
                    updatePersonalInfoRequestDto.setNewAvatarUrl(s);
                }
            }

            log.info("更新个人信息，用户ID: {}, 真实姓名: {}, 电话: {}, 邮箱: {}, 新头像地址: {}", updatePersonalInfoRequestDto.getUserId(), updatePersonalInfoRequestDto.getRealName(), updatePersonalInfoRequestDto.getPhone(), updatePersonalInfoRequestDto.getEmail(), updatePersonalInfoRequestDto.getNewAvatarUrl());
            Integer n = activityMapper.updatePersonalInfo(updatePersonalInfoRequestDto);
            if (n <= 0) {
                throw new BusinessException(500, "更新个人信息失败");
            }
            if (updatePersonalInfoRequestDto.getNewAvatarUrl() != null) {
                //最后删除OSS原始图片
                Boolean b = fileOssService.deleteFileFromOss(updatePersonalInfoRequestDto.getOriginalAvatarUrl());
                log.info("删除OSS原始图片，原始图片地址: {}", b);
            }
            //返回更新后的用户信息
            UserVo userVo = activityMapper.selectUserInfo(updatePersonalInfoRequestDto.getUserId());
            return userVo;
        } catch (Exception e) {
            e.printStackTrace();
            fileOssService.deleteFileFromOss(updatePersonalInfoRequestDto.getNewAvatarUrl());
            throw new BusinessException(500, "更新个人信息失败");
        }

    }



    private String getRegistrationStatusText(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 0:
                return "待审核";
            case 1:
                return "已通过";
            case 2:
                return "已拒绝";
            default:
                return "未知";
        }
    }


}
